import {assign, cloneDeep} from "lodash";
import {FormInstance} from "ant-design-vue";
import qs from "qs";
import { message } from 'ant-design-vue';

export interface FormOption<D = any>{
    query: () => void | Promise<any>,
    formVisible:boolean,
    isUpdate:boolean,
    formData:D,
    apiPrefix: string,
    saveApi: (data:D) => void | Promise<any>,
    deleteApi: (ids: string[])=>void | Promise<any>
}

/**
 * 同意表单操作
 * apiPrefix 为必传项
 * state.saveApi为保存和更新方法
 * state.deleteApi删除方法
 */
export function useForm<T extends {id: string}>(_options:Partial<FormOption>){
    const formState = reactive<FormOption>(assign(
        {
            formVisible:false,
            isUpdate:false,
            query(){},
            formData:{},
            // 必传项
            apiPrefix: "",
            saveApi: (data:T)=>{
                if(formState.apiPrefix){
                    return usePost(`${formState.apiPrefix}/saveOrUpdate`,data,{})
                }
            },
            deleteApi:(ids: string[])=>{
                if(formState.apiPrefix){
                    return useDelete(`${formState.apiPrefix}/delete`,{ids},{
                        paramsSerializer: (params) => {
                            return qs.stringify(params, { arrayFormat: 'comma' });
                        }
                    })
                }
            },
            idColumn:"id"
        }
        ,_options))

    const formRef = ref<FormInstance>()

    async function handleOk() {
        try {
            await formRef.value?.validate()
            // 新增或者编辑接口...
            formState.saveApi(formState.formData)?.then((res:any)=>{
                if(res.status == 200){
                    message.success(res.msg)
                    formState.formVisible = false
                    formState.query()
                }else{
                    message.error(res.msg)
                }
            })
        }
        catch (errorInfo) {
            console.log('Form Validate Failed:', errorInfo)
        }
    }

    function handleCancel() {
        formRef.value?.resetFields()
    }
    function openForm(record?: T) {
        formState.formVisible = true
        formState.isUpdate = !!record?.id
        formState.formData = cloneDeep(record) ?? {
        }
    }
    function handleAdd() {
        openForm()
    }

    function handleEdit(record: T) {
        openForm(record)
    }
    async function handleDelete(record: T) {
        console.log("删除")
        if (!record.id)
            return message.error('id 不能为空')
        try {
            const res = await formState.deleteApi([record.id])
            if (res.status === 200)
                formState.query()
            message.success('删除成功')
        }
        catch (e) {
            console.log(e)
        }
        finally {
            close()
        }
    }

    return {
        formState,
        handleOk,
        handleCancel,
        message,
        handleAdd,
        handleEdit,
        handleDelete,
        formRef,
        openForm
    }
}